/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-12-05     yoyoyes      first version
 */

#include "thread_mutex_demo1.h"

static rt_mutex_t dynamic_mutex = RT_NULL;
static rt_uint8_t number1, number2 = 0;

ALIGN(RT_ALIGN_SIZE)

static char thread1_stack[1024];
static struct rt_thread thread1;

/*
 * @brief  线程1入口函数
 *
 * @param  parameter 线程1入口函数参数
 *
 * @return None
 */
static void rt_thread1_entry(void *parameter)
{
    while(1)
    {
        /* 获取互斥量 */
        rt_mutex_take(dynamic_mutex, RT_WAITING_FOREVER);
        number1++;
        rt_thread_mdelay(10);
        number2++;
        /* 释放互斥量 */
        rt_mutex_release(dynamic_mutex);
    }
}

ALIGN(RT_ALIGN_SIZE)

static char thread2_stack[1024];
static struct rt_thread thread2;

/*
 * @brief  线程2入口函数
 *
 * @param  parameter 线程2入口函数参数
 *
 * @return None
 */
static void rt_thread2_entry(void *parameter)
{
    while(1)
    {
        rt_mutex_take(dynamic_mutex, RT_WAITING_FOREVER);
        if(number1 != number2)
        {
            rt_kprintf("not protect.number1 = %d, number2 = %d\n", number1, number2);
        }
        else
        {
            rt_kprintf("mutex protect, number1 = number2 is %d\n", number1);
        }

        number1++;
        number2++;

        rt_mutex_release(dynamic_mutex);

        if(number1 >= 50)
            return;
    }
}

/*
 * @brief  互斥量Demo1函数
 *
 * @param  None
 *
 * @return None
 */
int thread_mutex_demo1(void)
{
    /* 创建一个动态互斥量 */
    dynamic_mutex = rt_mutex_create("dmutex", RT_IPC_FLAG_PRIO);
    if(dynamic_mutex == RT_NULL)
    {
        rt_kprintf("create dynamic mutex failed.\n");
        return -1;
    }

    rt_thread_init(&thread1, "thread1", rt_thread1_entry, RT_NULL, &thread1_stack[0], sizeof(thread1_stack), THREAD_PRIORITY, THREAD_TIMESLICE);
    rt_thread_startup(&thread1);

    rt_thread_init(&thread2, "thread2", rt_thread2_entry, RT_NULL, &thread2_stack[0], sizeof(thread2_stack), THREAD_PRIORITY - 1, THREAD_TIMESLICE);
    rt_thread_startup(&thread2);

    return 0;
}





